package com.zlj.user.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zlj.user.domain.User;
import com.zlj.user.service.UserException;
import com.zlj.user.service.UserService;

import cn.itcast.commons.CommonUtils;

/**
 * User的登录servlet
 * @author bashen
 *
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");  //设置响应编码
		
		UserService userService = new UserService();
		
		/*
		 * 1、封装表单数据到Request域中
		 * 2、调用service的Login()方法，得到返回的User对象
		 *   > 如果抛出异常，把异常信息和User对象保存到request域中，转发到login.jsp页面
		 *   > 如果没有抛出异常，则把User对象保存到session中，重定向到welcome.jsp页面
		 */
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		
		try {
			User user = userService.login(form);
			
			//如果没有抛出异常，则保存User到session中
			request.getSession().setAttribute("user",user.getUsername());
			
			//重定向到成功页面
			response.sendRedirect(request.getContextPath() + "/user/welcome.jsp");
		} catch (UserException e) {
			request.setAttribute("msg", "用户名不存在！");
			request.setAttribute("user", form);
			request.getRequestDispatcher("/user/login.jsp").forward(request, response);
		}
	}
}
